<template>
  <div class="wise-crud">
    <div class="table-show">
      <div class="operation-block">
        <el-row class="oper-btn" :gutter="10" style="margin-bottom: 20px">
          <el-col :span="20">
            <div v-if="handle.indexOf('filters') !== -1">
              <wise-filters-form :columns="filtersItem" @on-filters="filtersHandle" />
            </div>
          </el-col>
        </el-row>
        <el-row class="oper-btn" :gutter="10" style="margin-bottom: 20px">
          <el-col :span="20">
            <el-button v-if="handle.indexOf('add') !== -1" type="primary" @click="handleAdd()">
              <i class="el-icon-plus" />
              添加
            </el-button>
            <slot name="outHandle" />
            <el-button
              v-if="handle.indexOf('export') !== -1 && urls.export"
              v-loading.fullscreen.lock="fullscreenLoading"
              type="info"
              @click="handleBeforeExport()"
            >
              <i class="el-icon-download" />
              导出
            </el-button>
            <el-button
              v-if="handle.indexOf('exportytg') !== -1 && urls.exportytg"
              v-loading.fullscreen.lock="fullscreenLoading"
              type="info"
              @click="handleBeforeExportytg()"
            >
              <i class="el-icon-download" />
              导出已通过计划
            </el-button>
            <el-button
              v-if="handle.indexOf('exporjcjl') !== -1 && urls.exporjcjl"
              v-loading.fullscreen.lock="fullscreenLoading"
              type="info"
              @click="handleBeforeExporjcjl()"
            >
              <i class="el-icon-download" />
              导出检测记录
            </el-button>
          </el-col>
          <el-col :span="4" style="float: right">
            <el-input v-if="handle.indexOf('search') !== -1" v-model="search.key" placeholder="请输入搜索的关键字" style="width: 100%">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch(1)" />
            </el-input>
          </el-col>
        </el-row>
      </div>
      <wise-table 
      
        ref="wiseTable"
        :columns="columns"
        :url="urls.list"
        :search="search"
        :filters="dataFilters"
        :fields="dataFields"
        :filter-obj="filterObj"
        :table-row-class-name-fun="tableRowClassNameFun"
        :show-summary="showSummary"
        :summaries-exclude-list="summariesExcludeList"
        @selection-change="handleSelectionChange"
        @on-edit="handleEdit"
        @on-view="handleView"
        @on-delete="handleDelete"
      >
        <template v-slot:handle="slotProps">
          <slot name="handle" :row="slotProps.row" />
        </template>
      </wise-table>
    </div>
    <el-dialog ref="drawer" :title="title" :close-on-click-modal="false" :visible.sync="drawer" destroy-on-close>
      <div v-if="drawer" class="draw-body">
        <wise-form :columns="formItems" :loading="loading" :old-object="object" @on-submit="submitHandle" />
      </div>
    </el-dialog>
    <el-dialog
      ref="viewDrawer"
      title="查看"
      :close-on-click-modal="false"
      :visible.sync="viewDrawer"
      close-on-press-escape
      destroy-on-close
    >
      <div v-if="viewItems" class="draw-body">
        <wise-view :columns="viewItems" :object="object" />
      </div>
    </el-dialog>
    <el-dialog
      ref="exportDrawer"
      title="选择导出列"
      :close-on-click-modal="false"
      :visible.sync="exportDrawer"
      close-on-press-escape
      destroy-on-close
    >
      <div>
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0" />
        <el-checkbox-group v-model="checkedfields" @change="handleCheckedFieldsChange">
          <el-checkbox v-for="field in columns.filter(item => item.prop !== undefined)" :key="field.prop" :label="field.prop">
            {{ field.label }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="handleExport()">确定</el-button>
        <el-button @click="exportDrawer = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import WiseTable from './Table/wiseTable'
import WiseForm from './Form/wiseForm'
import { downloadHandle, postHandle } from '@/api'
import WiseView from './View/wiseView'
import WiseFiltersForm from './Filters/wiseFiltersForm'
export default {
  name: 'WiseCrud',
  components: { WiseFiltersForm, WiseView, WiseForm, WiseTable },
  props: {
    urls: {
      type: Object,
      required: true
    },
    fields: {
      type: Array,
      required: true
    },
    filters: {
      type: Array
    },
    dataFields: {
      type: Array
    },
    filterObj: {
      type: Object
    },
    showSummary: {
      type: Boolean,
      default: false
    },
    summariesExcludeList: {
      type: Array,
      default: () => {
        return []
      }
    },
    tableRowClassNameFun: {
      type: Function
    },
    exporBeforeHandle: {
      type: Function
    },
    handle: {
      type: Array,
      default: () => {
        return ['add', 'search']
      }
    }
  },
  data() {
    return {
      columns: [],
      search: {
        key: '',
        fields: []
      },
      loading: false,
      formItems: [],
      submitLoading: false,
      object: {},
      drawer: false,
      title: '',
      viewDrawer: false,

      exportDrawer: false,
      checkAll: false,
      checkedfields: [],
      isIndeterminate: true,

      viewItems: [],
      filtersItem: [],
      dataFilters: [],
      fullscreenLoading: false
    }
  },
  mounted() {
    this.init()
    this.setFiltersItem()
    if (this.filters && this.filters.length > 0) {
      this.filters.forEach(item => {
        this.dataFilters.push(item)
      })
    }
    // this.dataFilters = this.filters ? this.filters : []
  },
  methods: {
    init() {
      this.columns = []
      this.search.fields = []
      if (this.fields && this.fields.length > 0) {
        this.fields.forEach(item => {
          if (item.use.indexOf('table') !== -1) {
            this.columns.push({
              label: item.label,
              type: item.tableType ? item.tableType : item.type,
              sortable: item.sortable,
              prop: item.prop,
              dataDic: item.dataDic,
              objKeys: item.objKeys,
              fixed: item.fixed,
              format: item.format,
              handle: item.handle,
              active: item.active,
              inactive: item.inactive,
              activeValue: item.activeValue,
              inactiveValue: item.inactiveValue,
              render: item.tableRender,
              url: item.url,
              width: item.tableWidth
            })
          }
          if (item.use.indexOf('search') !== -1) {
            this.search.fields.push(item.prop)
          }
        })
      }
    },
    setFiltersItem() {
      this.filtersItem = []
      if (this.fields && this.fields.length > 0) {
        this.fields.forEach(item => {
          if (item.use.indexOf('filters') !== -1) {
            this.filtersItem.push({
              label: item.label,
              type: item.type,
              prop: item.prop,
              dataDic: item.dataDic,
              labelWidth: item.labelWidth,
              filterable: item.filterable,
              url: item.url,
              labelKey: item.labelKey,
              valueKey: item.valueKey,
              objKeys: item.objKeys,
              filters: item.filters,
              operator: item.operator,
              render: item.formRender,
              filtersObj: item.filtersObj,
              defaultValue: item.defaultValue,
              fun: item.fun,
              desc: item.desc
            })
          }
        })
      }
    },
    setFromItem(hanlde) {
      this.formItems = []
      if (this.fields && this.fields.length > 0) {
        this.fields.forEach(item => {
          if (item.use.indexOf(hanlde) !== -1) {
            this.formItems.push({
              label: item.label,
              type: item.type,
              prop: item.prop,
              text: item.text,
              dataDic: item.dataDic,
              labelWidth: item.labelWidth,
              rules: item.rules,
              url: item.url,
              limit: item.limit,
              labelKey: item.labelKey,
              valueKey: item.valueKey,
              objKeys: item.objKeys,
              maxlength: item.maxlength,
              filters: item.filters,
              placeholder: item.placeholder,
              precision: item.precision,
              min: item.min,
              uploadType: item.uploadType,
              disabled: item[hanlde + 'Disabled'],
              render: item.formRender,
              filtersObj: item.filtersObj,
              defaultValue: item.defaultValue,
              accept: item.accept,
              town: item.town,
              fun: item.fun,
              desc: item.desc,
              objParams: item.objParams
            })
          }
        })
      }
    },
    setViewItem() {
      this.viewItems = []
      if (this.fields && this.fields.length > 0) {
        this.fields.forEach(item => {
          if (item.use.indexOf('view') !== -1) {
            this.viewItems.push({
              label: item.label,
              type: item.type,
              prop: item.prop,
              objKeys: item.objKeys,
              format: item.format,
              labelWidth: item.labelWidth,
              dataDic: item.dataDic,
              render: item.viewRender,
              uploadType: item.uploadType
            })
          }
        })
      }
    },
    getObjectById(id) {
      this.object = {}
      postHandle(this.urls.show + id, {}).then(response => {
        this.object = response.result
      })
    },
    deleteObjectById(id) {
      postHandle(this.urls.delete + id, {})
        .then(response => {
          this.$refs['wiseTable'].refresh()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(error => {
          const data = error.response.data
          for (const key in data) {
            this.$message.error(this.$t(key + '.' + data[key]))
          }
        })
    },
    handleAdd() {
      this.object = {}
      this.setFromItem('add')
      this.title = '新增'
      this.drawer = true
    },

    handleBeforeExport() {
      if (
        this.dataFilters.some(item => {
          return this.filtersItem.map(item => item.prop).indexOf(item.field) != -1
        })
      ) {
        this.exportDrawer = true
      } else {
        this.$message.error('请选过滤您需要导出的数据')
      }
    },
    handleBeforeExportytg() {
      this.$prompt('请输入导出文件名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.fullscreenLoading = true
          let params = {
            d: {
              filters: this.dataFilters,
              search: this.search
            },
            obj: {
              exportCodes: []
            }
          }
          // params.obj.exportCodes = this.columns
          //   .filter(item => this.checkedfields.includes(item.prop))
          //   .map(item => ({ name: item.label, code: item.prop }))

          // if (typeof this.exporBeforeHandle === 'function') {
          //   params = this.exporBeforeHandle(params)
          // }
          downloadHandle(this.urls.exportytg, params)
            .then(res => {
              this.fullscreenLoading = false
              this.exportDrawer = false
              let disposition = res.headers['content-disposition'].replace(/\"/g, '').split('=')
              let fileName = decodeURI(disposition[disposition.length - 1])
              let blob = new Blob([res.data], { type: res.data.type })
              let downloadElement = document.createElement('a')
              let href = window.URL.createObjectURL(blob) // 创建下载的链接
              downloadElement.href = href
              downloadElement.download = value || fileName // 下载后文件名
              document.body.appendChild(downloadElement)
              downloadElement.click() // 点击下载
              document.body.removeChild(downloadElement) // 下载完成移除元素
              window.URL.revokeObjectURL(href) // 释放blob对象
            })
            .catch(error => {
              this.fullscreenLoading = false
              const data = error.response.data
              for (const key in data) {
                this.$message.error(this.$t(key + '.' + data[key]))
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          })
        })
    },
    handleBeforeExporjcjl() {
      if (
        this.dataFilters.some(item => {
          return this.filtersItem.map(item => item.prop).indexOf(item.field) != -1
        })
      ) {
        this.dataFilters.some(item => {
          return this.filtersItem.map(item => item.prop).indexOf(item.field) != -1
        })

        this.$prompt('请输入检测时间间隔', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.fullscreenLoading = true
          let params = {
            d: {
              filters: this.dataFilters,
              search: this.search
            },
            objx: {
              exportCodes: []
            },
             sjc: value
          }
          // params.obj.exportCodes = this.columns
          //   .filter(item => this.checkedfields.includes(item.prop))
          //   .map(item => ({ name: item.label, code: item.prop }))

          // if (typeof this.exporBeforeHandle === 'function') {
          //   params = this.exporBeforeHandle(params)
          // }
          downloadHandle(this.urls.exporjcjl, params)
            .then(res => {
              this.fullscreenLoading = false
              this.exportDrawer = false
              let disposition = res.headers['content-disposition'].replace(/\"/g, '').split('=')
              let fileName = decodeURI(disposition[disposition.length - 1])
              let blob = new Blob([res.data], { type: res.data.type })
              let downloadElement = document.createElement('a')
              let href = window.URL.createObjectURL(blob) // 创建下载的链接
              downloadElement.href = href
              downloadElement.download = '气体检测报告' // 下载后文件名
              document.body.appendChild(downloadElement)
              downloadElement.click() // 点击下载
              document.body.removeChild(downloadElement) // 下载完成移除元素
              window.URL.revokeObjectURL(href) // 释放blob对象
            })
            .catch(error => {
              console.log(error)
              // this.fullscreenLoading = false
              // const data = error.response.data
              // for (const key in data) {
              //   this.$message.error(this.$t(key + '.' + data[key]))
              // }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          })
        })

      } else {
        this.$message.error('请选过滤您需要导出的数据')
      }


      
       
         
      
   
       
    },
    handleCheckAllChange(val) {
      this.checkedfields = val ? this.columns.filter(item => item.prop !== undefined).map(item => item.prop) : []
      this.isIndeterminate = false
    },
    handleCheckedFieldsChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.columns.filter(item => item.prop !== undefined).length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.columns.filter(item => item.prop !== undefined).length
    },

    handleExport() {
      this.$prompt('请输入自定义名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.fullscreenLoading = true
          let params = {
            d: {
              filters: this.dataFilters,
              search: this.search
            },
            obj: {
              exportCodes: []
            }
          }
          params.obj.exportCodes = this.columns
            .filter(item => this.checkedfields.includes(item.prop))
            .map(item => ({ name: item.label, code: item.prop }))

          if (typeof this.exporBeforeHandle === 'function') {
            params = this.exporBeforeHandle(params)
          }
          downloadHandle(this.urls.export, params)
            .then(res => {
              this.fullscreenLoading = false
              this.exportDrawer = false
              let disposition = res.headers['content-disposition'].replace(/\"/g, '').split('=')
              let fileName = decodeURI(disposition[disposition.length - 1])
              let blob = new Blob([res.data], { type: res.data.type })
              let downloadElement = document.createElement('a')
              let href = window.URL.createObjectURL(blob) // 创建下载的链接
              downloadElement.href = href
              downloadElement.download = value || fileName // 下载后文件名
              document.body.appendChild(downloadElement)
              downloadElement.click() // 点击下载
              document.body.removeChild(downloadElement) // 下载完成移除元素
              window.URL.revokeObjectURL(href) // 释放blob对象
            })
            .catch(error => {
              this.fullscreenLoading = false
              const data = error.response.data
              for (const key in data) {
                this.$message.error(this.$t(key + '.' + data[key]))
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          })
        })
    },

    handleEdit(row) {
      this.setFromItem('edit')
      this.title = '编辑'
      this.getObjectById(row.id)
      this.drawer = true
    },
    handleView(row) {
      this.setViewItem()
      this.getObjectById(row.id)
      this.viewDrawer = true
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteObjectById(row.id)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    submitHandle(obj) {
      this.loading = true
      let url = this.urls.add
      if (this.title === '驳回') {
        url = this.urls.rejected
      } else {
        url = this.urls.add
        if (obj.id) {
          url = this.urls.update + obj.id
        }
      }
       
      
      if(url.indexOf("/video/create")>0||url.indexOf("/video/update")>0||url.indexOf("/video-comb/create")>0||url.indexOf("/video-comb/update")>0 ){
        //obj.url="ezopen://open.ys7.com/"+obj.deviceSerial+"/1.hd.live";
        //obj.url="ezopen://open.ys7.com/E55087299/1.hd.live"+obj.channelNo+".flv";
        // obj.appKey="b8929dd935a64816867b547a607aece8";
        // obj.appSecret="b7245102fec53eb2fba2432c34633cec";
      }
      postHandle(url, { obj })
        .then(response => {
          this.$message('操作成功')
          this.loading = false
          this.drawer = false
          this.$refs['wiseTable'].refresh()
          // this.$refs['drawer'].closeDrawer()
        })
        .catch(error => {
          this.loading = false
          const data = error.response.data
          for (const key in data) {
            this.$message.error(this.$t(key + '.' + data[key]))
          }
        })
    },
    handleSearch(page) {
      this.$refs['wiseTable'].refresh(page)
    },
    filtersHandle(filters) {
      if (filters && filters.length > 0) {
        filters.forEach(item => {
          if (this.dataFilters && this.dataFilters.length > 0) {
            let n = this.dataFilters.findIndex(d => d.field === item.field)
            if (n !== -1) {
              this.dataFilters[n] = item
            } else {
              this.dataFilters.push(item)
            }
          } else {
            this.dataFilters = filters
          }
        })
      } else {
        this.dataFilters = []
        if (this.filters && this.filters.length > 0) {
          this.filters.forEach(item => {
            this.dataFilters.push(item)
          })
        }
      }

      this.$nextTick(() => {
        this.$refs['wiseTable'].refresh()
      })
    },
    handleSelectionChange(val) {
      this.$emit('selection-change', val)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-checkbox-group {
  .el-checkbox {
    margin-bottom: 8px;
    .el-checkbox__label {
      width: 100px;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
</style>
